<template>
  <div class="tag-log-container">
    <div class="search-section">
      <div class="search-title">搜索信息</div>
      
      <div class="search-form">
        <el-form :inline="true" size="small" :model="searchForm">
          <el-form-item label="UUID">
            <el-input v-model="searchForm.uid" placeholder="请输入用户UUID" style="width: 200px;" type="number"></el-input>
          </el-form-item>
          
          <el-form-item label="创建时间">
            <el-date-picker
              v-model="searchForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              style="width: 380px;">
            </el-date-picker>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" icon="el-icon-search" @click="handleSearch">搜索</el-button>
            <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
    
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>TAG日志</span>
        <el-button 
          type="success" 
          size="small" 
          icon="el-icon-download"
          style="float: right;"
          @click="exportData"
          :loading="exportLoading">
          导出CSV
        </el-button>
      </div>
      
      <el-table
        :data="tableData"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="id" label="ID" width="80" sortable></el-table-column>
        <el-table-column prop="uid" label="UUID" width="150"></el-table-column>
        <!-- <el-table-column prop="tag" label="标签" width="100"></el-table-column> -->
        <el-table-column prop="desc" label="备注" min-width="180"></el-table-column>
        <el-table-column prop="create_time" label="创建时间" width="170"></el-table-column>
      </el-table>
      
      <div class="pagination-container">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { playerTagRecord } from '@/api/user'
import { exportDataToCsv } from '@/utils/export'

export default {
  name: 'TagLog',
  data() {
    return {
      searchForm: {
        uid: '',
        timeRange: [
          this.getLastMonthDate(),
          new Date()
        ]
      },
      loading: false,
      exportLoading: false,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0
    };
  },
  created() {
    this.fetchData();
  },
  methods: {
    getLastMonthDate() {
      const date = new Date();
      date.setMonth(date.getMonth() - 1);
      return date;
    },
    async fetchData() {
      this.loading = true;
      try {
        const params = {
          page: this.currentPage,
          page_size: this.pageSize,
          uid: this.searchForm.uid ? parseInt(this.searchForm.uid) : 0,
          channel: 0 // 固定值0表示任意渠道
        }
        
        // 如果有时间范围，添加时间参数
        if (this.searchForm.timeRange && this.searchForm.timeRange.length === 2) {
          params.begin_time = this.searchForm.timeRange[0]
          params.end_time = this.searchForm.timeRange[1]
        }
        
        console.log('===== TagLog Debug Info =====')
        console.log('发送参数:', params)
        
        const response = await playerTagRecord(params)
        console.log('接口返回完整数据:', response)
        
        if (response && response.code === 0) {
          // 尝试多种可能的数据结构
          let records = []
          if (response.data && response.data.records && Array.isArray(response.data.records)) {
            records = response.data.records
          } else if (response.data && response.data.list && Array.isArray(response.data.list)) {
            records = response.data.list
          } else if (Array.isArray(response.data)) {
            records = response.data
          } else if (response.data && response.data.data && Array.isArray(response.data.data)) {
            records = response.data.data
          }
          
          console.log('解析后的records:', records)
          this.tableData = records
          
          // 处理总数
          if (response.data && response.data.total_page) {
            this.total = response.data.total_page * this.pageSize
          } else if (response.data && response.data.total) {
            this.total = response.data.total
          } else if (response.total_page) {
            this.total = response.total_page * this.pageSize
          } else if (response.total) {
            this.total = response.total
          } else {
            this.total = records.length
          }
          
          console.log('设置tableData长度:', this.tableData.length)
          console.log('设置total:', this.total)
          
        } else {
          console.error('接口返回错误:', response)
          this.$message.error(response.msg || response.message || '获取数据失败')
        }
      } catch (error) {
        console.error('获取TAG日志失败:', error)
        this.$message.error('获取数据失败: ' + error.message)
      } finally {
        this.loading = false;
      }
    },
    handleSearch() {
      this.currentPage = 1;
      this.fetchData();
    },
    handleReset() {
      this.searchForm = {
        uid: '',
        timeRange: [
          this.getLastMonthDate(),
          new Date()
        ]
      };
      this.handleSearch();
    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      this.fetchData();
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.fetchData();
    },
    async exportData() {
      this.exportLoading = true
      try {
        const params = {
          page: 1,
          page_size: 10000,
          uid: this.searchForm.uid ? parseInt(this.searchForm.uid) : 0,
          channel: 0
        }
        
        if (this.searchForm.timeRange && this.searchForm.timeRange.length === 2) {
          params.begin_time = this.searchForm.timeRange[0]
          params.end_time = this.searchForm.timeRange[1]
        }
        
        const response = await playerTagRecord(params)
        const allData = response.data.records || []
        
        const columns = [
          { prop: 'id', label: 'ID' },
          { prop: 'uid', label: 'UUID' },
          { prop: 'desc', label: '备注' },
          { prop: 'create_time', label: '创建时间' }
        ]
        
        const now = new Date()
        const dateStr = now.getFullYear() + 
          String(now.getMonth() + 1).padStart(2, '0') + 
          String(now.getDate()).padStart(2, '0') + '_' +
          String(now.getHours()).padStart(2, '0') + 
          String(now.getMinutes()).padStart(2, '0')
        
        const fileName = `TAG日志_${dateStr}.csv`
        exportDataToCsv(allData, columns, fileName)
        this.$message.success('导出成功！')
      } catch (error) {
        this.$message.error('导出失败')
        console.error(error)
      } finally {
        this.exportLoading = false
      }
    },
    handlePrint() {
      window.print();
    },
    refreshTable() {
      this.fetchData();
      this.$message({
        type: 'success',
        message: '数据已刷新'
      });
    }
  }
};
</script>

<style scoped>
.tag-log-container {
  padding: 20px;
  background-color: #fff;
}

.search-section {
  margin-bottom: 20px;
  padding: 10px 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
}

.search-title {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #333;
}

.table-section {
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  padding: 10px 20px;
}

.table-options {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
}

.left-buttons {
  display: flex;
  align-items: center;
}

.right-buttons {
  display: flex;
  align-items: center;
}

.right-buttons .el-button {
  margin-left: 8px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style> 